package Week5.J0515;

// dfs, 如何获得不同走位下的最小值?

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class 走迷宫_xv {
    static int n, m, x1, y1, x2, y2;
    static int N = 1010;
    static int[] dx = {1, 0, -1, 0};
    static int[] dy = {0, -1, 0, 1};

    static char[][] arr = new char[N][N];
    static int[][] dist = new int[N][N];

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt(); m = scanner.nextInt();

        x1 = scanner.nextInt(); y1 = scanner.nextInt();
        x2 = scanner.nextInt(); y2 = scanner.nextInt();

        for (int i = 1; i <= n; i++) {
            String tmp = scanner.next();
            for (int j = 1; j < m; j++) {
                arr[i][j] = tmp.charAt(j-1);
            }
        }

        System.out.println(bfs());
    }

    private static int bfs() {
        if (arr[x2][y2] == '*') {
            return -1;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                dist[i][j] = -1;
            }
        }
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{x1, y1});
        dist[x1][y1] = 0;

        while (!q.isEmpty()) {
            int[] t = q.poll();
             int a = t[0]; int b = t[1];
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if (x >= 1 && x <= n && y >= 1 && y <= m
                        && arr[x][y] == '.' && dist[x][y] == -1) {
                    q.add(new int[]{x, y});
                    dist[x][y] = dist[a][b] + 1;
                    if (x == x2 && y == y2) {
                        return dist[x][y];
                    }
                }
            }
        }
        return -1;
    }
}
